package com.simu.towercrane.fragments;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import uk.co.senab.photoview.PhotoViewAttacher;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.Toast;
import cc.util.android.view.CCPullLisvtView;
import cc.util.android.view.CCPullLisvtView.CCOnListViewListener;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVRelation;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.cn.adapters.ImageAndTextListAdapter;
import com.cn.adapters.ImageAndTextListAdapter.ImageListenr;
import com.simu.towercrane.R;

public class FragmentErShou extends BaseFragmentTwo {

	View mview = null;
	AVQuery<AVObject> query;
	AVQuery<AVObject> queryImg;
	final int FITSTSHOWNUM = 10;
	private Boolean IsTheEnd = false;
	int currentWhere;
	final int LOADMORENUM = 10;
	private ImageAndTextListAdapter ershouListAdapter;
	private static final double EARTH_RADIUS = 6378137;
	private List<Map<String, Object>> mList;

	private CCPullLisvtView mListView;
	private double latitude = 0.0;
	private double longitude = 0.0;
	private String addr;
	private ImageView ivcertified;
	// xyb
	ImageView mGestureImageView;
	// PopupWindow popWindow;
	PhotoViewAttacher mAttacher;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		if (mview == null) {
			Log.d("fragmentLife", "FragmentOneonCreateView");
			mview = inflater.inflate(R.layout.fragment_glasses_ershou, null);

		}
		Tool.destroyParent(mview);
		SharedPreferences SP = getActivity().getSharedPreferences("user", 0);
		latitude = Double.valueOf(SP.getString("latitude", "0")).doubleValue();
		longitude = Double.valueOf(SP.getString("lontitude", "0"))
				.doubleValue();
		addr = SP.getString("addr", "");
		// getlocation();
		addproduct();

		return mview;

	}

	public void addproduct() {
		mList = new ArrayList<Map<String, Object>>();
		// mSimpleAdapter = new SimpleAdapter(getActivity(), mList,
		// R.layout.listview_ershou_item,
		// new String[]
		// {"name","summary","price","effectiveDate","location","address"},
		// new int[]
		// {R.id.Resellname,R.id.Resellsummary,R.id.ReselltitlepriceNum,
		// R.id.ReselleffectimeDate,R.id.Reselllocation,R.id.Reselladdress
		// });

		ershouListAdapter = new ImageAndTextListAdapter(getActivity(), mList,
				R.layout.listview_ershou_item, new String[] { "name",
						"summary", "price", "effectiveDate", "location",
						"address", "ReselltitlecertifiedInfo", "connect",
						"collection", "share" }, new int[] {
						R.id.Resellname_ershou, R.id.Resellsummary,
						R.id.ReselltitlepriceNum, R.id.ReselleffectimeDate,
						R.id.Reselllocation, R.id.Reselladdress,
						R.id.ReselltitlecertifiedInfo, R.id.ResellconnectImg,
						R.id.Resellclloction, R.id.Resellshare });

		mListView = (CCPullLisvtView) mview.findViewById(R.id.my_list);

		ershouListAdapter.setImageListener(new ImageListenr() {

			@Override
			public void responeImageListner(ImageView imageView) {
				// TODO Auto-generated method stub
				View view = LayoutInflater.from(getActivity()).inflate(
						R.layout.second_hand_pop, null);
				Drawable drawable = imageView.getDrawable();
				mGestureImageView = (ImageView) view
						.findViewById(R.id.iv_photo);
				mGestureImageView.setImageDrawable(drawable);
				PopupWindow popWindow = new PopupWindow(view, getView()
						.getWidth(), getView().getHeight(), true);
				/*
				 * popWindow.setContentView(view);
				 * popWindow.setWidth(getView().getWidth());
				 * popWindow.setHeight(getView().getWidth())
				 */;
				popWindow.setBackgroundDrawable(view.getBackground());
				popWindow.showAtLocation(getView(), Gravity.CENTER, 0, 10);
			}

		});
		mListView.setAdapter(ershouListAdapter);

		mListView.setCCOnListViewListener(new CCOnListViewListener() {

			@Override
			public void onRefresh(CCPullLisvtView view) {
				// TODO Auto-generated method stub
				IsTheEnd = false;
				query = new AVQuery<AVObject>("Commodity");
				query.include("certifiedinfo");
				query.include("vendor");
				query.setLimit(FITSTSHOWNUM);
				query.findInBackground(new FindCallback<AVObject>() {

					@SuppressWarnings("unused")
					@Override
					public void done(List<AVObject> list, AVException arg1) {
						// TODO Auto-generated method stub
						if (list != null) {
							mList.clear();
							if (list.size() < FITSTSHOWNUM) {
								IsTheEnd = true;
							}
							if (list != null) {

								// query.include("image");
								// query.findInBackground(new
								// FindCallback<AVObject>() {
								//
								// @Override
								// public void done(List<AVObject> list,
								// AVException arg1) {
								// // TODO Auto-generated method stub
								// if(list!=null){
								// for(int i=0;i<list.size();i++){
								// AVObject parent=list.get(i);
								// parent.getString("name");
								// AVRelation<AVObject>
								// avRelation=parent.getRelation("image");
								// AVQuery<AVObject>
								// avQuery=avRelation.getQuery();
								// avQuery.findInBackground(new
								// FindCallback<AVObject>(){
								//
								// @Override
								// public void done(List<AVObject> arg0,
								// AVException arg1) {
								// // TODO Auto-generated method stub
								// //arg0.get(0);
								// }
								// });
								// }
								// }
								// }
								// });

								for (int i = 0; i < list.size(); i++) {

									// mview.findViewById(R.id.ReselltitlecertifiedInfo).setVisibility(View.INVISIBLE);

									currentWhere = list.size();
									final HashMap<String, Object> map = new HashMap();
									// list.get(i).getAVObject("vendor").getString("vendorName");
									// list.get(i).getAVObject("certifiedInfo");
									List<AVObject> listpint = new ArrayList<AVObject>();
									listpint.add(list.get(i).getAVObject(
											"certifiedInfo"));
									if (listpint.toString().equals("[null]")) {
										map.put("iscertifiedInfo",
												"NOTcertifiedInfo");

									} else
										map.put("iscertifiedInfo",
												"certifiedInfo");

									// 是否收藏
									map.put("ObjectId", list.get(i)
											.getObjectId());
									AVUser user = AVUser.getCurrentUser();
									AVRelation<AVObject> relation = user
											.getRelation("watchedCommodity");
									AVQuery<AVObject> avQuerycollect = relation
											.getQuery();

									avQuerycollect
											.findInBackground(new FindCallback<AVObject>() {

												@Override
												public void done(
														List<AVObject> productlist,
														AVException arg1) {
													// TODO Auto-generated
													// method stub
													if (productlist != null) {
														for (AVObject product : productlist) {
															if (product
																	.getObjectId()
																	.equals(map
																			.get("ObjectId"))) {
																map.put("collected",
																		"collected");
															} else {
																map.put("collected",
																		"notcollected");
															}

														}
													} else {
														map.put("collected",
																"notcollected");
													}
												}
											});

									AVObject parent = list.get(i);
									parent.getString("name");
									AVRelation<AVObject> avRelation = parent
											.getRelation("image");

									AVQuery<AVObject> avQuery = avRelation
											.getQuery();
									avQuery.findInBackground(new FindCallback<AVObject>() {

										@Override
										public void done(List<AVObject> arg0,
												AVException arg1) {
											// TODO Auto-generated method stub
											// arg0.get(0);
											// String name=arg0.get(0)+"e ";
											// AVObject avobject = new
											// AVObject("image");
											if (arg0 != null) {
												ArrayList<String> listImage = new ArrayList<String>();
												listImage.clear();
												for (int k = 0; k < arg0.size(); k++) {
													AVObject avobject = arg0
															.get(k);
													String rui = arg0.get(k)
															.get("image") + "";
													AVFile avFile = avobject
															.getAVFile("image");
													String url = avFile
															.getUrl();
													listImage.add(url);

												}

												map.put("url", listImage);
											}
											ershouListAdapter
													.notifyDataSetChanged();

										}
									});
									map.put("addr", addr);
									map.put("tel",
											list.get(i).getAVObject("vendor")
													.getString("tel"));

									map.put("name",
											list.get(i).getString("name"));

									map.put("summary",
											list.get(i).getString("summary"));
									map.put("price",
											"￥" + list.get(i).getInt("price")
													+ "");
									map.put("objectID", list.get(i)
											.getObjectId());
									map.put("share", "分享");

									double latitudeproduct;
									double longitudeproduct;
									if (list.get(i).getAVGeoPoint("location") != null) {
										latitudeproduct = list.get(i)
												.getAVGeoPoint("location")
												.getLatitude();
										longitudeproduct = list.get(i)
												.getAVGeoPoint("location")
												.getLongitude();
									} else {
										latitudeproduct = latitude;
										longitudeproduct = longitude;

									}

									double Distance = DistanceOfTwoPoints(
											latitude, longitude,
											latitudeproduct, longitudeproduct);
									map.put("latitude", latitude);
									map.put("longitude", longitude);
									map.put("latitudeproduct", latitudeproduct);
									map.put("longitudeproduct",
											longitudeproduct);
									int distance = (int) Distance;
									if (Distance < 1000) {
										map.put("location", distance + "M");
									} else {
										map.put("location", distance / 1000
												+ "KM");
									}

									SimpleDateFormat sdf = new SimpleDateFormat(
											"yyyy-MM-dd HH:mm:ss ");

									if (list.get(i).getDate("expiryDate") != null) {
										String textday = sdf.format(list.get(i)
												.getDate("expiryDate"));

										map.put("effectiveDate", textday);
									}
									// map.put("expiryDate",
									// list.get(i).getString("expiryDate"));

									map.put("address",
											list.get(i).getString("address"));

									// map.put("certifiedInfo",
									// list.get(i).getString("certifiedInfo"));
									// map.put("isResell",
									// list.get(i).getString("isResell"));
									// String uri=list.get(i).get("image")+"";

									// group=
									// (ViewGroup)getView().findViewById(R.id.list_item_layout).findViewById(R.id.viewGroup);
									// ImageView[] imageViews = new
									// ImageView[2];
									// for (int j = 0; j < imageViews.length;
									// j++) {
									// ImageView imageView = new
									// ImageView(getView().getContext());
									// imageView.setLayoutParams(new
									// LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
									// imageViews[j] = imageView;
									// //ImageView
									// IV1=(ImageView)getActivity().findViewById(R.id.ResellIV);
									// //
									// ImageLoader.getInstance().displayImage(uri,
									// IV1);
									// imageView.setImageResource(R.drawable.ic_launcher);
									// group.addView(imageView);
									// }

									// map.put("age",
									// list.get(i).getString("age"));
									mList.add(map);
									// ershouListAdapter.notifyDataSetChanged();
									// mSimpleAdapter.notifyDataSetChanged();
								}

							}
							// Log.d("onRefresh", "list size"+list.size());
							// Log.d("onRefresh","currentWhere "+ currentWhere);
							mListView.stopRefresh();
						}
					}
				});

			}

			@Override
			public void onLoadMore(CCPullLisvtView view) {
				// TODO Auto-generated method stub
				if (!IsTheEnd) {
					query = new AVQuery<AVObject>("Commodity");
					query.skip(currentWhere);
					query.setLimit(LOADMORENUM);
					query.findInBackground(new FindCallback<AVObject>() {

						@Override
						public void done(List<AVObject> list, AVException arg1) {
							if (list != null) {
								currentWhere += list.size();
								if (list.size() < LOADMORENUM) {
									IsTheEnd = true;
								}
								if (list.size() == 0) {
									Toast.makeText(
											getActivity()
													.getApplicationContext(),
											"数据加载完毕 共" + currentWhere + "条数据",
											1000).show();

								}

								if (list != null) {

									for (int i = 0; i < list.size(); i++) {

										currentWhere = list.size();
										final HashMap<String, Object> map = new HashMap();
										List<AVObject> listpint = new ArrayList<AVObject>();
										listpint.add(list.get(i).getAVObject(
												"certifiedInfo"));
										if (listpint.toString().equals("[null]")) {
											map.put("iscertifiedInfo",
													"NOTcertifiedInfo");

										} else
											map.put("iscertifiedInfo",
													"certifiedInfo");
										map.put("ObjectId", list.get(i)
												.getObjectId());
										AVUser user = AVUser.getCurrentUser();
										AVRelation<AVObject> relation = user
												.getRelation("watchedCommodity");
										AVQuery<AVObject> avQuerycollect = relation
												.getQuery();

										avQuerycollect
												.findInBackground(new FindCallback<AVObject>() {

													@Override
													public void done(
															List<AVObject> productlist,
															AVException arg1) {
														// TODO Auto-generated
														// method stub
														if (productlist != null) {
															for (AVObject product : productlist) {
																if (product
																		.getObjectId()
																		.equals(map
																				.get("ObjectId"))) {
																	map.put("collected",
																			"collected");
																} else {
																	map.put("collected",
																			"notcollected");
																}

															}
														} else {
															map.put("collected",
																	"notcollected");
														}
													}
												});

										AVObject parent = list.get(i);
										parent.getString("name");
										AVRelation<AVObject> avRelation = parent
												.getRelation("image");

										AVQuery<AVObject> avQuery = avRelation
												.getQuery();
										avQuery.findInBackground(new FindCallback<AVObject>() {

											@Override
											public void done(
													List<AVObject> arg0,
													AVException arg1) {
												if (arg0 != null) {
													ArrayList<String> listImage = new ArrayList<String>();
													listImage.clear();
													for (int k = 0; k < arg0
															.size(); k++) {
														AVObject avobject = arg0
																.get(k);
														String rui = arg0
																.get(k)
																.get("image")
																+ "";
														AVFile avFile = avobject
																.getAVFile("image");
														String url = avFile
																.getUrl();
														listImage.add(url);

													}
													map.put("url", listImage);
												}
												ershouListAdapter
														.notifyDataSetChanged();

											}
										});

										map.put("addr", addr);
										map.put("tel",
												list.get(i).getAVObject("vendor")
														.getString("tel"));
										map.put("name",
												list.get(i).getString("name"));

										map.put("summary",
												list.get(i).getString("summary"));
										map.put("price",
												"￥" + list.get(i).getInt("price")
														+ "");
										map.put("objectID", list.get(i)
												.getObjectId());
										map.put("share", "分享");
										double latitudeproduct;
										double longitudeproduct;
										if (list.get(i).getAVGeoPoint(
												"location") != null) {
											latitudeproduct = list.get(i)
													.getAVGeoPoint("location")
													.getLatitude();
											longitudeproduct = list.get(i)
													.getAVGeoPoint("location")
													.getLongitude();
										} else {
											latitudeproduct = latitude;
											longitudeproduct = longitude;

										}
										double Distance = DistanceOfTwoPoints(
												latitude, longitude,
												latitudeproduct,
												longitudeproduct);
										map.put("latitude", latitude);
										map.put("longitude", longitude);
										map.put("latitudeproduct", latitudeproduct);
										map.put("longitudeproduct",
												longitudeproduct);
										int distance = (int) Distance;
										if (Distance < 1000) {
											map.put("location", distance + "M");
										} else {
											map.put("location", distance / 1000
													+ "KM");
										}

										SimpleDateFormat sdf = new SimpleDateFormat(
												"yyyy-MM-dd HH:mm:ss ");

										if (list.get(i).getDate("expiryDate") != null) {
											String textday = sdf.format(list
													.get(i).getDate(
															"expiryDate"));

											map.put("effectiveDate", textday);
										}

										map.put("address", list.get(i)
												.getString("address"));
										mList.add(map);
									}

								}

								mListView.stopLoadMore();
							}
						}

					});
				} else {
					mListView.stopLoadMore();
					Toast.makeText(getActivity(), "已经全部加载完", Toast.LENGTH_LONG);
				}
			}
		});
	}

	public void getlocation() {
		LocationManager locationManager = (LocationManager) getActivity()
				.getSystemService(Context.LOCATION_SERVICE);
		if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			Location location = locationManager
					.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			if (location != null) {
				latitude = location.getLatitude();
				longitude = location.getLongitude();
			} else {
				LocationListener locationListener = new LocationListener() {

					// Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
					@Override
					public void onStatusChanged(String provider, int status,
							Bundle extras) {

					}

					// Provider被enable时触发此函数，比如GPS被打开
					@Override
					public void onProviderEnabled(String provider) {

					}

					// Provider被disable时触发此函数，比如GPS被关闭
					@Override
					public void onProviderDisabled(String provider) {

					}

					// 当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
					@Override
					public void onLocationChanged(Location location) {
						if (location != null) {
							Log.e("Map",
									"Location changed : Lat: "
											+ location.getLatitude() + " Lng: "
											+ location.getLongitude());
							latitude = location.getLatitude(); // 经度
							longitude = location.getLongitude(); // 纬度
						}
					}
				};
				locationManager.requestLocationUpdates(
						LocationManager.NETWORK_PROVIDER, 1000, 0,
						locationListener);
				Location location1 = locationManager
						.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
				if (location1 != null) {
					latitude = location1.getLatitude(); // 经度
					longitude = location1.getLongitude(); // 纬度
				}
			}
		}
	}

	public static double rad(double d) {
		return d * Math.PI / 180.0;
	}

	public static double DistanceOfTwoPoints(double lat1, double lng1,
			double lat2, double lng2) {
		double radLat1 = rad(lat1);
		double radLat2 = rad(lat2);
		double a = radLat1 - radLat2;
		double b = rad(lng1) - rad(lng2);
		double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
				+ Math.cos(radLat1) * Math.cos(radLat2)
				* Math.pow(Math.sin(b / 2), 2)));
		s = s * EARTH_RADIUS;
		s = Math.round(s * 10000) / 10000;
		return s;
	}
}
